package work.atpgroup.controller.administrator;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import work.atpgroup.entity.ResourceLink;
import work.atpgroup.entity.User;
import work.atpgroup.entity.tool.ApplicationProperties;
import work.atpgroup.entity.tool.FileEraser;
import work.atpgroup.service.ResourceService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Objects;

@Controller
public class ResourceController {
    @Resource(name="resourceService")
    private ResourceService resourceService;

    @RequestMapping("admin/static-file-list")
    public String getAdminFilePage(Model model, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        ArrayList<ResourceLink> resourceLinks = (ArrayList<ResourceLink>) resourceService.getResourceLinkByUserId(user.getUserId());
        model.addAttribute("resources",resourceLinks);
        return "admin/resource";
    }
    @RequestMapping("admin/static-file-list/delete/{deleteResourceId}")
    public void deleteResource(@PathVariable String deleteResourceId, HttpSession session){
        User user = (User)session.getAttribute("user");
        int deleteResId = Integer.parseInt(deleteResourceId);
        ResourceLink resourceLink = resourceService.getResourceLinkById(deleteResId);
        if(Objects.equals(user.getUserId(),resourceLink.getUserId())){
            //删除数据库相关记录和本地文件
            resourceService.deleteResourceLinkById(deleteResId);
            System.out.println("FileEraser Erase File "+ ApplicationProperties.getAbsoluteLocalPath(resourceLink.getPath())+
                    ((FileEraser.erase(resourceLink.getPath()))?
                    "成功": "失败"));
        }
    }
    @GetMapping("/resource_upload/page")
    public String upload_page(){
        return "admin/resource_upload";
    }
}
